package sql;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Schema;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * Flink SQL UDTF
 */
public class UDTFSQLDemo {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // 注册函数
        tableEnv.registerFunction("Split",new Split(","));

        DataStreamSource<String> socketTextStream = env.socketTextStream("localhost", 8888);

        Table table = tableEnv.fromDataStream(socketTextStream, $("line"));
        tableEnv.createTemporaryView("t_word", table);

        Table res = tableEnv.sqlQuery("SELECT word FROM t_word, LATERAL TABLE(Split(line)) as A(word)");


        // 非聚合Table 将表格转成AppendStream
        tableEnv.toDataStream(res).print();

        env.execute("UDTFSQLDemo");
    }
}
